package com.eva.databuilder.builders.cms;

import com.eva.cms.biz.article.CmsArticleBiz;
import com.eva.cms.biz.article.dto.QueryCmsArticleDTO;
import com.eva.cms.biz.article.vo.CmsArticleProfileVO;
import com.eva.databuilder.builders.AbstractTemplateDataBuilder;
import com.eva.databuilder.bo.TemplateDataParameters;
import com.eva.constants.CmsArticleStatusEnum;
import com.eva.framework.cache.CacheProxy;
import com.eva.framework.common.model.PageData;
import com.eva.framework.common.model.PageWrap;
import com.eva.framework.config.AppConfig;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 构建多个栏目的文章列表数据
 */
@Component
public class MultipleCategoryArticlesBuilder extends AbstractTemplateDataBuilder<Map<String, List<CmsArticleProfileVO>>> {

    private static final String PARAMETER_CATEGORY_UIDS = "categoryUids";

    @Resource
    private CmsArticleBiz cmsArticleBiz;

    @Resource
    private CacheProxy<String, List<CmsArticleProfileVO>> cacheProxy;

    @Resource
    private AppConfig appConfig;

    @Override
    public Map<String, List<CmsArticleProfileVO>> build(TemplateDataParameters parameters) {
        List<String> categoryUids = parameters.getList(PARAMETER_CATEGORY_UIDS, Collections.emptyList());
        if (CollectionUtils.isEmpty(categoryUids)) {
            return Collections.emptyMap();
        }
        Map<String, List<CmsArticleProfileVO>> result = new HashMap<>();
        for (String categoryUid : categoryUids) {
            String cacheKey = "category:" + categoryUid + ":articles";
            List<CmsArticleProfileVO> cacheData = cacheProxy.get(cacheKey);
            if (cacheData != null) {
                result.put(categoryUid, cacheData);
                continue;
            }
            PageWrap<QueryCmsArticleDTO> pageWrap = new PageWrap<>();
            pageWrap.setPage(1);
            pageWrap.setCapacity(8);
            pageWrap.setModel(QueryCmsArticleDTO
                    .builder()
                    .categoryUid(categoryUid)
                    .status(CmsArticleStatusEnum.ONLINE.name())
                    .build());
            PageData<CmsArticleProfileVO> pageData = cmsArticleBiz.findProfilePage(pageWrap);
            result.put(categoryUid, pageData.getRecords());
            cacheProxy.put(cacheKey, pageData.getRecords(), appConfig.getTemplateDataCacheExpire());
        }
        return result;
    }
}
